/**
 * Create By FengZheng
 * On 2019/10/8 19:53
 */
(function ($) {
    let $input = {
        student: $("#student"),
        subject: $("#select-box"),
        money: $("#money"),
        classNum: $("#class-num"),
        comment: $("#comment")
    };

    let $dom = {
        errorBox: $("#error-box"),
        errorContent: $("#error-content"),
        submit: $("#submit"),
        disableBtn: false
    };

    /**
     * 点击了提交
     */
    $dom.submit.on("click",function () {
        // 按钮禁用
        $dom.submit.attr("disabled",true);
        $dom.disableBtn = true;

        // 获取学生
        let studentId = $input.student.selectpicker('val');
        studentId = parseInt(studentId);
        if(studentId === 0){
            return openErrorBox("请选择学生");
        }

        // 获取科目
        let subject = $input.subject.attr("data-id");
        if(subject === undefined || subject === null){
            return openErrorBox("请选择科目");
        }

        // 获取金额
        let money = $input.money.val();
        if(money.length !== 0){
            let reg = /^\d{1,5}[.]\d{2}$/;
            if(!reg.test(money)){
                return openErrorBox("请输入正确的金额，精确到小数点后两位");
            }
        }

        // 获取课时数
        let classNum = $input.classNum.val();
        if(classNum.length !== 0){
            let reg = /^\d{1,3}$/;
            if(!reg.test(classNum)){
                return openErrorBox("请输入正确的课时数，限制输入1~999");
            }
        }

        // 获取备注
        let comment = $input.comment.val();
        if(comment.length > 250){
            return openErrorBox("备注不能超过85个字符");
        }

        $.ajax({
            url: "/admin/frame/addStudentOrder",
            type: "post",
            dataType: "json",
            data: {
                student: studentId,
                subject: subject,
                money: money,
                classNum: classNum,
                comment: comment
            },
            success: function (resultD) {
                if( (typeof resultD) === "object" ){
                    let status = resultD.status;
                    if(status === 200){
                        alert("添加成功！");
                        return window.location.reload();
                    }
                    return openErrorBox(resultD.info);
                }
                openErrorBox("服务器返回异常信息，请稍后重试");
            },
            error: function (jqXHR) {
                openErrorBox(jqXHR.status);
            }
        });
    });

    /**
     * 打开错误提示
     */
    function openErrorBox(msg) {
        $dom.errorContent.text(msg);
        $dom.errorBox.modal("show");

        if($dom.disableBtn){
            $dom.submit.attr("disabled",false);
            $dom.disableBtn = false;
        }
    }
}(window.jQuery));


/**
 * 查询学生信息
 */
(function ($) {
    "use strict";

    let studentInfo = null;
    let $dom = {
        $stuInput: $("#student")
    };

    /**
     * 查询所有的学生信息
     */
    function queryAllStudent(){
        $.ajax({
            url: "/admin/frame/queryAllStudentsName",
            type: "post",
            dataType: "json",
            success: function (resultD) {
                if( (typeof resultD) === "object" ){
                    let status = resultD.status;
                    if(status === 200){
                        let info = resultD.info;

                        if( (typeof info) === "string" ){
                            info = JSON.parse(info);
                        }
                        studentInfo = info;

                        for(let i=0,len=info.length; i<len; i++){
                            let name = info[i].name;
                            let realName = info[i].realName;
                            realName = (realName === undefined ? "" : realName);
                            let option = "<option value='"+ info[i].id +"' data-tokens='"+name+" "+realName+"'>"+ name + "【"+ realName +"】</option>";
                            $dom.$stuInput.append(option);
                        }

                        $dom.$stuInput.selectpicker("refresh");
                    }
                }
            }
        });
    }

    $(document).ready(function () {
        let stuTimer = window.setTimeout(function () {
            $.fn.selectpicker.Constructor.BootstrapVersion = '3';
            $dom.$stuInput.selectpicker();
            queryAllStudent();
            window.clearTimeout(stuTimer);
        },2000);
    });
})(window.jQuery);

/**
 * 查询科目信息
 */
(function ($) {
    "use strict";

    let subjectInfo = null;

    let $dom = {
        selectBox: $("#select-box"),
        selectA: $("#select-1"),
        selectB: $("#select-2"),
        selectC: $("#select-3"),
        selectForm: $("#subject")
    };

    let system = {
        selectBoxShow: false,
        gradeSecName: "",
        gradeName: "",
        subjectName: "",
        lastGradeSec: null,
        lastGrade: null,
        lastSubject: null
    };

    /**
     * 开始选择
     */
    $dom.selectForm.on("click",function () {
        if(subjectInfo !== null && system.selectBoxShow !== true){
            $dom.selectBox.removeClass("hidden");
            system.selectBoxShow = true;
        }
    });

    /**
     * 鼠标移出选择框区域
     */
    $dom.selectBox.mouseleave(function () {
        if(system.selectBoxShow){
            let cTimer = window.setTimeout(function () {
                $dom.selectBox.addClass("hidden");
                system.selectBoxShow = false;
                window.clearTimeout(cTimer);
            },2000);
        }
    });

    /**
     * 年级段被点击
     */
    $dom.selectA.on("click",function (ev) {
        let childLen = $dom.selectA.children("div").length;
        if(childLen <= 0){
            return;
        }

        let event = ev || window.event;
        let target = event.target || event.srcElement;

        system.gradeSecName = $(target).text();

        // 更新年级
        changeGrade(system.gradeSecName);
        gradeSecActive(target);
    });

    /**
     * 年级被点击
     */
    $dom.selectB.on("click",function (ev) {
        let childLen = $dom.selectB.children("div").length;
        if(childLen <= 0){
            return;
        }

        let event = ev || window.event;
        let target = event.target || event.srcElement;

        system.gradeName = $(target).text();

        // 更新科目
        changeSubject();
        gradeActive(target);
    });

    /**
     * 科目被点击
     */
    $dom.selectC.on("click",function (ev) {
        let childLen = $dom.selectC.children("div").length;
        if(childLen <= 0){
            return;
        }

        let event = ev || window.event;
        let target = event.target || event.srcElement;

        system.subjectName = $(target).text();

        let cSelectId = $(target).attr("data-id");
        $dom.selectBox.attr("data-id",cSelectId);
        $dom.selectForm.text(system.gradeSecName+"/"+system.gradeName+"/"+$(target).text());

        // 科目激活
        subjectActive(target);
    });

    /**
     * 查询科目信息
     */
    function querySubjectInfo(){
        $.ajax({
            url: "/query/subject",
            type: "post",
            dataType: "json",
            success: function (resultD) {
                if( (typeof resultD) == "object" ){
                    let status = resultD.status;
                    if(status === 200){
                        let info = resultD.info;

                        if( (typeof info) === "string" ){
                            info = JSON.parse(info);
                        }

                        let gradeSecArray = [];
                        subjectInfo = info;

                        // 清空原数据
                        $dom.selectA.empty();
                        $dom.selectB.empty();
                        $dom.selectC.empty();

                        for(let i=0; i<info.length; i++){
                            let gradeSec = info[i].gradeSection;
                            if(gradeSecArray.indexOf(gradeSec) === -1){
                                gradeSecArray.push(gradeSec);
                                $dom.selectA.append("<div class='select-item'>"+gradeSec+"</div>");
                            }
                        }
                    }
                }else{
                    console.error("获取年级信息时服务器响应异常！")
                }
            },
            error: function () {
                console.error("不能获取到年级信息！");
            }
        });
    }

    /**
     * 更新年级
     */
    function changeGrade(gradeSec) {
        if(subjectInfo !== null){
            let cGradeArray = [];
            $dom.selectB.empty();

            for(let i=0; i<subjectInfo.length; i++){
                if(subjectInfo[i].gradeSection === gradeSec){
                    let cGrade = subjectInfo[i].grade;
                    if(cGradeArray.indexOf(cGrade) === -1){
                        cGradeArray.push(cGrade);
                        $dom.selectB.append("<div data-id='"+subjectInfo[i].id+"' class='select-item'>"+cGrade+"</div>");
                    }
                }
            }
        }
    }

    /**
     * 年级段激活
     */
    function gradeSecActive(target) {
        if(system.lastGradeSec !== null){
            $(system.lastGradeSec).removeClass("select-item-active");
        }
        $(target).addClass("select-item-active");
        system.lastGradeSec = target;
    }

    /**
     * 更新科目
     */
    function changeSubject() {
        if(subjectInfo !== null){
            let cSubjectArray = [];
            $dom.selectC.empty();

            for(let i=0; i<subjectInfo.length; i++){
                if(subjectInfo[i].grade === system.gradeName && subjectInfo[i].gradeSection === system.gradeSecName){
                    let cSubject = subjectInfo[i].subName;
                    if(cSubjectArray.indexOf(cSubject) === -1){
                        cSubjectArray.push(cSubject);
                        $dom.selectC.append("<div data-id='"+subjectInfo[i].id+"' class='select-item'>"+cSubject+"</div>");
                    }
                }
            }
        }
    }

    /**
     * 年级激活
     */
    function gradeActive(target) {
        if(system.lastGrade !== null){
            $(system.lastGrade).removeClass("select-item-active");
        }
        $(target).addClass("select-item-active");
        system.lastGrade = target;
    }

    /**
     * 科目激活
     */
    function subjectActive(target) {
        if(system.lastSubject !== null){
            $(system.lastSubject).removeClass("select-item-active");
        }
        $(target).addClass("select-item-active");
        system.lastGrade = target;
    }

    $(document).ready(function () {
        querySubjectInfo();
    });

})(window.jQuery);

/**
 * Bootstrap modal插件，无需修改
 */
(function ($) {
    'use strict';

    // MODAL CLASS DEFINITION
    // ======================

    let Modal = function (element, options) {
        this.options             = options;
        this.$body               = $(document.body);
        this.$element            = $(element);
        this.$dialog             = this.$element.find('.modal-dialog');
        this.$backdrop           = null;
        this.isShown             = null;
        this.originalBodyPad     = null;
        this.scrollbarWidth      = 0;
        this.ignoreBackdropClick = false;

        if (this.options.remote) {
            this.$element
                .find('.modal-content')
                .load(this.options.remote, $.proxy(function () {
                    this.$element.trigger('loaded.bs.modal')
                }, this))
        }
    };

    Modal.VERSION  = '3.3.7';

    Modal.TRANSITION_DURATION = 300;
    Modal.BACKDROP_TRANSITION_DURATION = 150;

    Modal.DEFAULTS = {
        backdrop: true,
        keyboard: true,
        show: true
    };

    Modal.prototype.toggle = function (_relatedTarget) {
        return this.isShown ? this.hide() : this.show(_relatedTarget)
    };

    Modal.prototype.show = function (_relatedTarget) {
        let that = this;
        let e    = $.Event('show.bs.modal', { relatedTarget: _relatedTarget });

        this.$element.trigger(e);

        if (this.isShown || e.isDefaultPrevented()) return;

        this.isShown = true;

        this.checkScrollbar();
        this.setScrollbar();
        this.$body.addClass('modal-open');

        this.escape();
        this.resize();

        this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this));

        this.$dialog.on('mousedown.dismiss.bs.modal', function () {
            that.$element.one('mouseup.dismiss.bs.modal', function (e) {
                if ($(e.target).is(that.$element)) that.ignoreBackdropClick = true
            })
        });

        this.backdrop(function () {
            let transition = $.support.transition && that.$element.hasClass('fade');

            if (!that.$element.parent().length) {
                that.$element.appendTo(that.$body) // don't move modals dom position
            }

            that.$element
                .show()
                .scrollTop(0);

            that.adjustDialog();

            if (transition) {
                that.$element[0].offsetWidth // force reflow
            }

            that.$element.addClass('in');

            that.enforceFocus();

            let e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget });

            transition ?
                that.$dialog // wait for modal to slide in
                    .one('bsTransitionEnd', function () {
                        that.$element.trigger('focus').trigger(e)
                    })
                    .emulateTransitionEnd(Modal.TRANSITION_DURATION) :
                that.$element.trigger('focus').trigger(e)
        })
    };

    Modal.prototype.hide = function (e) {
        if (e) e.preventDefault();

        e = $.Event('hide.bs.modal');

        this.$element.trigger(e);

        if (!this.isShown || e.isDefaultPrevented()) return;

        this.isShown = false;

        this.escape();
        this.resize();

        $(document).off('focusin.bs.modal');

        this.$element
            .removeClass('in')
            .off('click.dismiss.bs.modal')
            .off('mouseup.dismiss.bs.modal');

        this.$dialog.off('mousedown.dismiss.bs.modal');

        $.support.transition && this.$element.hasClass('fade') ?
            this.$element
                .one('bsTransitionEnd', $.proxy(this.hideModal, this))
                .emulateTransitionEnd(Modal.TRANSITION_DURATION) :
            this.hideModal()
    };

    Modal.prototype.enforceFocus = function () {
        $(document)
            .off('focusin.bs.modal') // guard against infinite focus loop
            .on('focusin.bs.modal', $.proxy(function (e) {
                if (document !== e.target &&
                    this.$element[0] !== e.target &&
                    !this.$element.has(e.target).length) {
                    this.$element.trigger('focus')
                }
            }, this))
    };

    Modal.prototype.escape = function () {
        if (this.isShown && this.options.keyboard) {
            this.$element.on('keydown.dismiss.bs.modal', $.proxy(function (e) {
                e.which === 27 && this.hide()
            }, this))
        } else if (!this.isShown) {
            this.$element.off('keydown.dismiss.bs.modal')
        }
    };

    Modal.prototype.resize = function () {
        if (this.isShown) {
            $(window).on('resize.bs.modal', $.proxy(this.handleUpdate, this))
        } else {
            $(window).off('resize.bs.modal')
        }
    };

    Modal.prototype.hideModal = function () {
        let that = this;
        this.$element.hide();
        this.backdrop(function () {
            that.$body.removeClass('modal-open');
            that.resetAdjustments();
            that.resetScrollbar();
            that.$element.trigger('hidden.bs.modal')
        })
    };

    Modal.prototype.removeBackdrop = function () {
        this.$backdrop && this.$backdrop.remove();
        this.$backdrop = null
    };

    Modal.prototype.backdrop = function (callback) {
        let that = this;
        let animate = this.$element.hasClass('fade') ? 'fade' : '';

        if (this.isShown && this.options.backdrop) {
            let doAnimate = $.support.transition && animate;

            this.$backdrop = $(document.createElement('div'))
                .addClass('modal-backdrop ' + animate)
                .appendTo(this.$body);

            this.$element.on('click.dismiss.bs.modal', $.proxy(function (e) {
                if (this.ignoreBackdropClick) {
                    this.ignoreBackdropClick = false;
                    return
                }
                if (e.target !== e.currentTarget) return;
                this.options.backdrop === 'static'
                    ? this.$element[0].focus()
                    : this.hide()
            }, this));

            if (doAnimate) this.$backdrop[0].offsetWidth; // force reflow

            this.$backdrop.addClass('in');

            if (!callback) return;

            doAnimate ?
                this.$backdrop
                    .one('bsTransitionEnd', callback)
                    .emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
                callback()

        } else if (!this.isShown && this.$backdrop) {
            this.$backdrop.removeClass('in');

            let callbackRemove = function () {
                that.removeBackdrop();
                callback && callback()
            };
            $.support.transition && this.$element.hasClass('fade') ?
                this.$backdrop
                    .one('bsTransitionEnd', callbackRemove)
                    .emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
                callbackRemove()

        } else if (callback) {
            callback()
        }
    };

    // these following methods are used to handle overflowing modals

    Modal.prototype.handleUpdate = function () {
        this.adjustDialog()
    };

    Modal.prototype.adjustDialog = function () {
        let modalIsOverflowing = this.$element[0].scrollHeight > document.documentElement.clientHeight;

        this.$element.css({
            paddingLeft:  !this.bodyIsOverflowing && modalIsOverflowing ? this.scrollbarWidth : '',
            paddingRight: this.bodyIsOverflowing && !modalIsOverflowing ? this.scrollbarWidth : ''
        })
    };

    Modal.prototype.resetAdjustments = function () {
        this.$element.css({
            paddingLeft: '',
            paddingRight: ''
        })
    };

    Modal.prototype.checkScrollbar = function () {
        let fullWindowWidth = window.innerWidth;
        if (!fullWindowWidth) { // workaround for missing window.innerWidth in IE8
            let documentElementRect = document.documentElement.getBoundingClientRect();
            fullWindowWidth = documentElementRect.right - Math.abs(documentElementRect.left)
        }
        this.bodyIsOverflowing = document.body.clientWidth < fullWindowWidth;
        this.scrollbarWidth = this.measureScrollbar()
    };

    Modal.prototype.setScrollbar = function () {
        let bodyPad = parseInt((this.$body.css('padding-right') || 0), 10);
        this.originalBodyPad = document.body.style.paddingRight || '';
        if (this.bodyIsOverflowing) this.$body.css('padding-right', bodyPad + this.scrollbarWidth)
    };

    Modal.prototype.resetScrollbar = function () {
        this.$body.css('padding-right', this.originalBodyPad)
    };

    Modal.prototype.measureScrollbar = function () { // thx walsh
        let scrollDiv = document.createElement('div');
        scrollDiv.className = 'modal-scrollbar-measure';
        this.$body.append(scrollDiv);
        let scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;
        this.$body[0].removeChild(scrollDiv);
        return scrollbarWidth
    };


    // MODAL PLUGIN DEFINITION
    // =======================

    function Plugin(option, _relatedTarget) {
        return this.each(function () {
            let $this   = $(this);
            let data    = $this.data('bs.modal');
            let options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option);

            if (!data) $this.data('bs.modal', (data = new Modal(this, options)));
            if (typeof option == 'string') data[option](_relatedTarget);
            else if (options.show) data.show(_relatedTarget)
        })
    }

    let old = $.fn.modal;

    $.fn.modal             = Plugin;
    $.fn.modal.Constructor = Modal;


    // MODAL NO CONFLICT
    // =================

    $.fn.modal.noConflict = function () {
        $.fn.modal = old;
        return this
    };


    // MODAL DATA-API
    // ==============

    $(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) {
        let $this   = $(this);
        let href    = $this.attr('href');
        let $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))); // strip for ie7
        let option  = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data());

        if ($this.is('a')) e.preventDefault();

        $target.one('show.bs.modal', function (showEvent) {
            if (showEvent.isDefaultPrevented()) return; // only register focus restorer if modal will actually get shown
            $target.one('hidden.bs.modal', function () {
                $this.is(':visible') && $this.trigger('focus')
            })
        });
        Plugin.call($target, option, this)
    })
})(window.jQuery);